<?php

class server
{
    protected $ip;
    protected $port;

    public function __construct($ip, $port)
    {
        $this->ip = $ip;
        $this->port = $port;
        $this->createSocket();
    }

    private function createSocket()
    {
        $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($sock < 0) {
            echo "Error:" . socket_strerror(socket_last_error()) . "\n";
        }

        $ret = socket_bind($sock, $this->ip, $this->port);
        if (!$ret) {
            echo "bind failed:" . socket_strerror(socket_last_error()) . "\n";
            exit;
        }
        echo "OK\n";

        $ret = socket_listen($sock);
        if ($ret < 0) {
            echo "listen failed:" . socket_strerror(socket_last_error()) . "\n";
        }

        do {
            $asock = socket_accept($sock);
            if ($asock < 0) {
                echo "accept failed:" . socket_strerror(socket_last_error()) . "\n";
            }

            $buf = socket_read($asock, 1024);

            echo "服务器端接收到的数据".$buf."\n";

            if (!$buf) {
                echo "read failed:" . socket_strerror(socket_last_error()) . "\n";

                break;
            }

            $msg = strrev($buf);


            socket_write($asock, $msg, strlen($msg));
            socket_close($asock);
            break;
        } while (TRUE);
        socket_close($sock);
    }

}

$server = new server("127.0.0.1", 8116);